<template>
    <!-- 添加或修改部门对话框 -->
    <el-dialog v-model="open" :title="form.id?'修改数据':'新增数据'" width="600px" append-to-body>
        <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
            <el-row>
                <el-col :span="24">
                    <el-form-item label="上级课程名称" prop="parentId">
                        <h3>{{ form.parentName }}</h3>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="课程名称" prop="name">
                        <el-input v-model="form.name" placeholder="请输入课程名称" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="备注" prop="remark">
                        <el-input v-model="form.remark" placeholder="请输入备注" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="显示排序" prop="orderNum">
                        <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
                    </el-form-item>
                </el-col>

                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="form.status">
                        <template v-for="item in sys_normal_disable" :key="item.value">
                            <el-radio :label="item.value">{{ item.label }}</el-radio>
                        </template>
                    </el-radio-group>
                </el-form-item>
            </el-row>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup="addAndeditCourse">
import { reactive, ref,getCurrentInstance, ComponentInternalInstance  } from 'vue';
import { type FormRules, type FormInstance, ElMessage } from 'element-plus';
import {SubmitForm} from '@/api/app/typescript/courseModel'
import {addCourse,updateCourse,getCourseById} from '@/api/app/course/course'
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable } = proxy!.useDict('sys_normal_disable');

const open = ref(false);
//得到数据表单form样式对象
const formRef = ref <FormInstance>();

//声明子组件的自定义事件 https://cn.vuejs.org/api/sfc-script-setup.html#defineprops-defineemits
const emit = defineEmits(['refreshDataList'])

const props = defineProps({
    subjectId:{
        type: Number
    }
})

   // 定义表单对象
   const form = ref<SubmitForm>({
       id: 0,
       parentId:0,
       parentName:'',
       subjectId:props.subjectId??0,
       ancestors:'',
       name: '',
       remark: '',
       orderNum:0,
       status: '0'
   });

      // 表单验证
      const rules = reactive<FormRules>({
        name: [
           { required: true, message: '该值不能为空', trigger: 'blur' }
       ],
       remark: [
           { required: true, message: '该值不能为空', trigger: 'blur' }
       ],
       orderNum: [
           { required: true, message: '该值不能为空', trigger: 'blur' }
       ],
       status: [
           { required: true, message: '该值不能为空', trigger: 'blur' }
       ],
   });
//对话框保存按钮
const submitForm = () => {
    formRef.value.validate((valid: boolean) => {
        //验证不成功
        if (!valid) {
            return false
        }

        //修改
        if (form.value.id) {
            updateCourse(form.value).then(resp => {
                ElMessage.success({
                    message: '修改成功',
                    duration: 500,
                    onClose: () => {
                        //关闭弹窗
                        open.value = false
                        //调用重新查询数据操作
                        emit('refreshDataList')
                    }
                });

            })
        } else {
            //新增
            addCourse(form.value).then(resp => {
                debugger;
                ElMessage.success({
                    message: '新增成功',
                    duration: 500,
                    onClose: () => {
                        //关闭弹窗
                        open.value = false
                        //调用重新查询数据操作
                        emit('refreshDataList')
                    }
                });

            })
        }

    })

};
//对话框取消按钮
const cancel = () => {
    open.value = false;
    resetFrom();
};

// 重置表单
const resetFrom = () => {
    // 清空表单样式
    if (formRef.value) {
        formRef.value.resetFields();
    }
    // 重置值
    form.value = {
        id: 0,
        parentId: 0,
        parentName: '',
        subjectId: props.subjectId??0,
        ancestors: '',
        name: '',
        remark: '',
        orderNum: 0,
        status: '0'
    };
};

//判断如果是修改操作，就要查询数据库，还原数据,要暴露出去
const init = (id?: number,pid?: number,pName?: string) => {
    open.value = true
   	// 重置表单数据
    resetFrom();
   	// id 存在则为修改,要还原数据
   	if (id) {
        getCourseById(id).then(resp=> {
             const data:SubmitForm=resp.data;
             //转换为字符串{"id":1}
             const str=JSON.stringify(data);
             //再一次把字符串还原成对象
             form.value=JSON.parse(str);
             console.log(form.value)
             
        })
   	 }else{
        if(pid==0){
            //显示根节点的名称
            form.value.parentId=0
            form.value.parentName='根节点'
        
        }else{
            form.value.parentId=pid??0;
            form.value.parentName=pName??''
        }
        
     }
   }

   defineExpose({
   	init
   })

</script>

<style lang="scss" scoped>

</style>